// pages/confirm_order/confirm_order.js
const getToken= require('../../utils/get_token.js');
var pood,memberId,openId='';
var feedbackApi = require('../common/showToast.js');
let cookie, token;
const ckToken = async (that) => {//token确认
  let nTime = Math.floor(new Date().getTime() / 1000);
  let oldTime = wx.getStorageSync('ntime') || 0;
  if (nTime < oldTime)//现在的时间小于到期时间
  {
    thou(that);
  } else {
    let tokens = await getToken.getToken();
    thou(that);
  }
}
const thou = (that) => {//token没有失效时执行的代码
  defaltAdd(that);
  demo(that);
}
const defaltAdd = function (that) {
  let params = [ 'common/receiver/list', {"id":memberId}]
  getToken.getData(function (res) {
    let sure = true;
    let listA = res.data.lists;
    let lists = '';
    if (!pood.zt) {//不是自提商品
      that.data.typeA = 1;
      for (let i = 0; i < listA.length; i++) {
        if (listA[i].isdefault) {
          lists = listA[i];
          sure = false;
        }
      }
      if (sure)//无默认地址
      {
        lists = listA[0]
      }
      that.data.addId = lists.id;
      if (!that.data.isNaSales)//是否有限制
      {
        checkArea(that);
      } else {
        that.setData({ ntShow: false })
      }
      that.setData({
        name: lists.name,
        phone: lists.mobile,
        address: lists.address,
        addId: that.data.addId
      })
    }
    else {
      that.data.typeA = 2;
      that.setData({
        ntShow: false,
        shipName: listA[0].name,
        shipMobile: Number(listA[0].mobile)
      })
    }
    that.setData({
      typeA: that.data.typeA
    })
  }, ...params)
};
const demo=function(that){
  let params = ['shop/goods/loadGoods', {"id":pood.productId,"totalProductQuantity":that.data.amount}]
  getToken.getData(function (res) {
    console.log(res.data)
    if (pood.classify == 1) {
      that.data.limit = res.data.bus[0].goods_list[0].A;
    } else {
      that.data.limit = pood.limit;
    }
    if (res.data.bus[0].goods_list[0].guige != '' && res.data.bus[0].goods_list[0].guige != null) {
      var guig = JSON.parse(res.data.bus[0].goods_list[0].guige);
      if(guig.length>0)
      {
        that.data.guige = '';
        for (let item of guig) {
          that.data.guige += item.name + ' ';
        }
        that.data.isSpecial=true;
      }
    }
    that.data.price=res.data.bus[0].goods_list[0].int_goods_price/100;
    res.data.bus[0].goods_list[0].goods_img='http://www.globalhexi.com/'+res.data.bus[0].goods_list[0].goods_img;
    res.data.bus[0].bus_logo='http://www.globalhexi.com/'+res.data.bus[0].bus_logo;
    that.setData({
      s: res.data,
      guige: that.data.guige,
      price:that.data.price,
      amount:that.data.amount,
      isSpecial:that.data.isSpecial,
      hidden: true
    })
  }, ...params)

}
const checkArea = (that) => {//验证地址
  let params = ['shop/pingTuan/isSupportSales', {"goodsId":that.data.goodsId,"id":that.data.addId}]
  getToken.getData(function (res) {
    if (res.data.flag && !res.data.isSupportSales) {
      that.setData({ ntShow: true })
    } else {
      that.setData({ ntShow: false })
    }
  }, ...params)
}
Page({
  data: {
  shipName: '',
  shipMobile: '',
	name:'',
	phone:'',
  address:'',
	addId:'',
	amount:1,
	memo:'',
	guige:'',
  goodsId:'',
  addresst:'',
  typeA:0,
  ntShow:true,
  isNaSales:false,
	loading: false,
	disabled: false,
  isSpecial:false,
	boolT:true,
	limit:1,
	s:{}
  },

  /**
   * 生命周期函数--监听页面加载 
   */
  onLoad: function (options) {
    let that = this;
    openId = wx.getStorageSync('openId') || '';
    memberId = wx.getStorageSync('memberId') || '';
    cookie = wx.getStorageSync('cookie') || '';
    token = wx.getStorageSync('token') || '';
    pood = wx.getStorageSync('pood') || '';
    console.log(pood)
    that.data.goodsId = pood.goodsId || '';
    that.data.isNaSales = pood.ntShow || false;
    if (pood.zt)
    {
      that.data.addId = pood.zitiAddressList[0].id;
      that.setData({
        addresst: pood.zitiAddressList[0]
      })
    }
  },
  onShow: function () {
	let that = this;
    ckToken(that);
  },
  nameBlur: function (e) {
    let that = this;
    e.detail.value = e.detail.value.replace(/\s/g, "");
    that.setData({
      shipName: e.detail.value
    })
  },
  phoneBlur: function (e) {
    let that = this;
    e.detail.value = e.detail.value.replace(/\s/g, "");
    that.setData({
      shipMobile: e.detail.value
    })
  },
	jian:function(e){
		var that=this;
		if (that.data.amount>1)
		{
			that.data.amount =that.data.amount- 1;
			demo(that);
		}
	},
	jia:function(e){
		var that = this;
		if (that.data.limit> that.data.amount){
			that.data.amount = that.data.amount +1;
			demo(that);
		}
	},
	blurT:function(e){
		this.setData({
			memo: e.detail.value
		})
	},
  changeAdd: function (e) {
    var that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      wx.redirectTo({
        url: '../l_address/l_address?page=confirm_order&id=' + pood.productId,
        success: function () {
          setTimeout(function () {
            that.data.boolT = true;
          }, 500)
        }
      })
    }
  },
  enterZt:function(e){
    var that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      wx.redirectTo({
        url: '../zt/zt?page=2&id=' + pood.productId,
        success: function () {
          setTimeout(function () {
            that.data.boolT = true;
          }, 500)
        }
      })
    }
  },
  go_sale: function (e) {
    let that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      wx.navigateTo({
        url: '../sale/sale?id=' + that.data.goodsId,
        success: function () {
          setTimeout(function () {
            that.data.boolT = true;
          }, 500)
        }
      })
    }
  },
	submitOrder:function(e){
    let that=this;
    if (pood.zt) {
      if (that.data.shipName == '') {
        feedbackApi.showToast({ title: '请先输入姓名！', mask: false });
        return false;
      }
      if (that.data.shipMobile == '') {
        feedbackApi.showToast({ title: '请先输入联系电话！', mask: false });
        return false;
      }
    }
    let shipName = that.data.shipName;//姓名
    let shipMobile = that.data.shipMobile;//电话
    let productId = pood.productId;//商品id
    let productQuantity=that.data.amount;//数量
    let receiverId = that.data.addId;//地址id
    let memo = that.data.memo;
    if (that.data.ntShow)
    {
      feedbackApi.showToast({ title: '对不起,您所选的地区不销售此商品', mask: false });
      return false;
    }
		that.setData({
			loading: true,
			disabled: true
		})
    let data = '{"openId":"' + openId + '","id":"' + productId + '","productQuantity":' + productQuantity + ',"memberId":"' + memberId + '","receiverId":"' + receiverId + '","memo":"' + memo + '","isMini":"mini","shipName":"' + shipName + '","shipMobile":"' + shipMobile +'"}';
    let params = [ 'shop', 'shop/order/createOrderForHexiSM', data]
    getToken.pay(function (res) {
      console.log(res.data);
      if (res.data.flag == true) {
        wx.requestPayment({
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': res.data.signType,
          'paySign': res.data.paySign,
          'success': function (res) {
            wx.navigateBack({
              delta: 1
            })
          },
          'fail': function (res) {
            console.log(res)
          }
        })
      } else {
        feedbackApi.showToast({ title: res.data.message, mask: false })//调用 showToast
      }
      that.setData({
        loading: false,
        disabled: false
      })
    }, ...params)
	},
 
  onShareAppMessage: function () {
  
  }
})